<template>
  <div id="container"></div>
</template>

<script>
import AMapLoader from "@amap/amap-jsapi-loader";
import { getequipmentlist } from '@/api/echarts';

export default {
  name: "map-view",
  data() {
    return {
      map: null,
      points: [],
      markers: [],
      cluster: null,
      district: {
        Beijing: { center: '116.405285,39.904989' },
        Shanghai: { center: '121.473701,31.230416' },
        Wuhan: { center: '114.305393,30.593099' },
        Guangzhou: { center: '113.264385,23.129112' },
        // other district centers...
      },
    };
  },
  created() {
    this.fetchEquipmentList();
  },
  mounted() {
    this.initAMap();
  },
  unmounted() {
    this.map?.destroy();
  },
  methods: {
    fetchEquipmentList() {
      getequipmentlist({ limit: 10000000 }).then(res => {
        this.points = res.msg
          .filter(item => item.lat && item.lng)
          .map(item => ({
            lnglat: [parseFloat(item.lng), parseFloat(item.lat)],
            district: item.district || 'Unknown',
          }));
        this.initMarkers();
        if (this.map) {
          this.initCluster();
        }
      }).catch(error => {
        console.error('Error fetching equipment list:', error);
      });
    },
    initAMap() {
      AMapLoader.load({
        key: "f8c954755588cd09132500151dc4d01c", // 申请好的Web端开发者Key
        version: "2.0", // 指定要加载的 JSAPI 的版本
        plugins: ["AMap.Scale", "AMap.MarkerClusterer", "AMap.Geolocation"], // 需要使用的插件列表
      })
        .then((AMap) => {
          this.map = new AMap.Map("container", {
            viewMode: "3D", // 是否为3D地图模式
            zoom: 4, // 初始化地图级别
            center: [116.397428, 39.90923], // 初始化地图中心点位置
            mapStyle: "amap://styles/blue", // 使用高德提供的地图样式
          });

          // 添加比例尺
          this.map.addControl(new AMap.Scale());

          // 浏览器定位
          this.map.plugin('AMap.Geolocation', () => {
            const geolocation = new AMap.Geolocation({
              enableHighAccuracy: true, // 是否使用高精度定位，默认:true
              timeout: 10000, // 超过10秒后停止定位，默认：5s
              buttonOffset: new AMap.Pixel(10, 20), // 定位按钮的停靠位置
              zoomToAccuracy: true, // 定位成功后是否自动调整地图视野到定位点
            });
            this.map.addControl(geolocation);
            geolocation.getCurrentPosition((status, result) => {
              if (status === 'complete') {
                this.map.setCenter(result.position);
              } else {
                console.error('Geolocation failed: ', result.message);
              }
            });
          });

          this.initMarkers();
          this.initCluster();
        })
        .catch((e) => {
          console.log(e);
        });
    },
    initMarkers() {
      this.markers = this.points.map(point => {
        return new AMap.Marker({
          position: point.lnglat,
          map: this.map,
          extData: point,
        });
      });
    },
    initCluster() {
      if (this.cluster) {
        this.cluster.setMap(null); // 清除现有的聚合
      }
      // 初始化聚合
      this.cluster = new AMap.MarkerClusterer(this.map, this.markers, {
        gridSize: 80,
        styles: this.getClusterStyles(),
      });
    },
    getClusterStyles() {
      return [
        {
          url: 'https://webapi.amap.com/theme/v1.3/markers/n/mark_b.png',
          size: new AMap.Size(40, 40),
          offset: new AMap.Pixel(-20, -20),
          textColor: '#fff',
          textSize: 16,
        }
      ];
    },
  },
};
</script>

<style scoped>
#container {
  width: 100%;
  height: 100%;
}
.amap-cluster {
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 14px;
  color: #fff;
  background: rgba(51,153,255,0.6);
  border-radius: 50%;
  width: 40px;
  height: 40px;
  text-align: center;
  line-height: 40px;
}
</style>
